// Program to generate overlays
program def segraph
	syntax varlist(min=1) [if] [in] [aweight], By(varname) [Axis2 Scale(real 1.96) ///
	SCHeme(passthru) SUBpop(varname numeric) NAME(passthru) Refline(string asis) Line ///
	xlabel(passthru) xtitle(passthru) xscale(passthru) SEtype(string) symbol_list(string) ///
	legend(passthru) ytitle(passthru) yscale(passthru) NOSE graphopt(string asis) ] 
	
	
	qui marksample touse 
	* qui markout `touse' `by', strok 
	* qui count if `touse' 
	* if r(N) == 0 error 2000 
	local nvars : word count `varlist'
	
	
	di `exp'
	
	preserve

	/// Reference Line
	if !missing("`refline'")  {
		foreach l in `refline' {
			local refline_value: di `l'
			local refline_list `refline_list' `refline_value'
		}
		local refline = "xline(`refline_list')"
	}

	if !missing("`line'") {
		local gtype "line"
	}
	else {
		local gtype "scatter"
	}

	qui foreach var of local varlist {
		if !missing("`subpop'") {
			levelsof `subpop' `if', local(subvars)
			local subcount: word count `subvars'
			if `subcount'>8 {
				di in red "That's to many subcategories! Try 8 or less."
				error 134
			}
			foreach sub of local subvars {
				tempvar mvar
				clonevar `mvar' = `var' if `subpop'==`sub'
				local subvarlab: var label `subpop'
				if ("`subvarlab'"=="") local subvarlab `subpop' 
				
				local sublabel: value label `subpop'

				if ("`sublabel'"!="") {
					local valuelab: label `sublabel' `sub'
				}
				else {
					local valuelab `sub'	
				}
				local `mvar'_lab: var label `var'
				if ("``mvar'_lab'"=="") local `mvar'_lab `var' 
				local `mvar'_lab "``mvar'_lab' - `subvarlab'=`valuelab'"

				clonevar `mvar'_sd = `mvar'
				local MVars `MVars' `mvar'
				local SDVars `SDVars' `mvar'_sd
			}
		}

		else {
			tempvar mvar
			clonevar `mvar' = `var'
			local `mvar'_lab: var label `var'
			if ("``mvar'_lab'"=="") local `mvar'_lab `var' 
			
			clonevar `mvar'_sd = `var'
			local MVars `MVars' `mvar'
			local SDVars `SDVars' `mvar'_sd
		}
	}

	* Determine standard error type
	if mi("`setype'") {
		local setype semean
	}
	else if substr("`setype'",1,3) == "seb" {
		local setype sebinomial	
	}
	else if "`setype'"=="sd" {
		local setype sd	
	}

	if "`setype'"=="sd" {
		local bartype "SD"
	}
	else {
		local bartype "SE"
	}
	collapse (mean) `MVars' (`setype') `SDVars'  `if' [`weight' `exp'], by(`by') fast

	local axisnum = 1
	local legend_opt "legend(order("
	local vcount = 1
	
	foreach mvar of local MVars {
		if "`symbol_list'" != "" {
			local var_index: list posof "`mvar'" in MVars
			local cur_symbol: word `var_index' of `symbol_list'
			local msymbol msymbol(`cur_symbol')
		}

		local legend_opt "`legend_opt' `vcount'"
		if mi("`nose'") {
			local increment = 2
		}
		else {
			local increment = 1
		}
		local vcount = `vcount' + `increment' 
		qui gen `mvar'_plus_sd = `mvar' + `mvar'_sd * `scale'
		qui gen `mvar'_minus_sd = `mvar' - `mvar'_sd * `scale'
		la var `mvar' "``mvar'_lab'"
		la var `mvar'_plus_sd "+`scale'`bartype'"
		la var `mvar'_minus_sd "-`scale'`bartype'"
		* Zero out rcap if noSE is specified
		if mi("`nose'") {
			local error_bars (rcap `mvar'_minus_sd `mvar'_plus_sd `by', yaxis(`axisnum'))
		}
		local g (`gtype' `mvar' `by', yaxis(`axisnum') `msymbol') `error_bars'
		local G `G' `g'
		if !missing("`axis2'") {
			local axisnum = 2
		}
	}
	local legend_opt "`legend_opt'))"
	twoway `G', `scheme' `name' `refline'  `legend_opt' `xlabel' `xtitle' `xscale' `legend' `ytitle' `yscale' `graphopt'
	restore

end




// Table 1
use working/sequential_records_with_geography, clear
gen white_nonmiss = white==1

estpost tabstat white white_nonmiss if city!="New York" & new_account & year>=1866, by(year)
esttab using output/white_depositor_arrival.txt, cells("white(fmt(4)) white_nonmiss") replace 	title("Table 1a: White Depositor Arrival by Year")



estpost tabstat white white_nonmiss if new_account & year>=1871, by(year)
esttab using output/white_depositor_arrival.txt, cells("white(fmt(4)) white_nonmiss") append 	title("Table 1b: With NY Branch")



// Table 2
clear
import delimited using data/interest_payments_valid_balance.csv

gen interest_rate = (amt/floor(min_balance_strict))*2 if inrange(dividend_number,15,19)
replace interest_rate = (amt/floor(min_balance_strict))*2 if inrange(dividend_number,14,14)
replace interest_rate = (amt/floor(min_balance_strict))*3 if inrange(dividend_number,6,13)
replace interest_rate = (amt/floor(min_balance_strict))*2 if inrange(dividend_number,4,5)
gen apr = interest_rate*100

table dividend_number, stat(p25 apr) stat(median apr) stat(p75 apr)  stat(count apr) nformat("%5.1f" p25 median p75) nformat( "%5.0f" count)  nototals
table dividend_number, stat(min max_balance ) stat(p5 max_balance ) nformat("%5.2f" min p5)  nototals

// Table 3
clear
use working/jay_cooke_window
* Drop Philadelphia, whose records are only include organizations, and which have only 1 and 11 new accounts over the 6 month period
drop if inlist(city,  "Philadelphia")

merge 1:1 city date using working/jay_cooke_window_demographics, nogen


generate byte ny = city == "New York"

gen dtnyc1000 = distance_to_nyc/1000
gen founded1870 = year_founded == 1870

* Drop sundays which have all been rolled back to the prior Satuday in the cleaning process
drop if dow(date) == 0
assert max_days_before>=30 & max_days_after>=30 /* Check that panel is full on both sides of the event */


gen bank_failure_state = inlist(state, "DC", "NY", "VA", "LA")
gen bank_failure_city = inlist(city, "Washington", "New York", "New Orleans", "Richmond")


eststo drop *
local win30 inrange(event_time,-30, 30) & event_time != 0
local win15 inrange(event_time,-15, 15) & event_time != 0
foreach regwindow in "win30" "win15" {
	eststo `regwindow'_1: qui ppmlhdfe new_accounts i1.post_event_date if ``regwindow'', a(bank) vce(cluster bank)
	estadd local bankfe "Y"
	
	eststo `regwindow'_2: qui ppmlhdfe new_accounts i1.post_event_date if ``regwindow'' & 	deposits_august_1872 >=100000, a(bank) vce(cluster bank)
	estadd local bankfe "Y"
	
	eststo `regwindow'_3: qui ppmlhdfe new_white_account i1.post_event_date  if ``regwindow'', a(bank) vce(cluster bank)
	estadd local bankfe "Y"

	eststo `regwindow'_4: qui ppmlhdfe new_local_account i1.post_event_date  if ``regwindow'', a(bank) vce(cluster bank)
	estadd local bankfe "Y"

	eststo `regwindow'_5: qui ppmlhdfe new_accounts i1.post_event_date##i1.ny if ``regwindow'', a(bank) vce(cluster bank)
	estadd local bankfe "Y"
	
	eststo `regwindow'_6: qui ppmlhdfe new_accounts i1.post_event_date##c.dtnyc1000 if ``regwindow'', a(bank) vce(cluster bank)
	estadd local bankfe "Y"
	
	eststo `regwindow'_7: qui ppmlhdfe new_accounts i1.post_event_date##bank_failure_state  if ``regwindow'', a(bank) vce(cluster bank)
	estadd local bankfe "Y"

}


la var new_accounts "New Accts"
la var dtnyc1000 "Distance to NY (1000 miles)"
la define ny 1 "New York Branch" 0 "Other Branch", replace
la define post_event 1 "Post Event" 0 "Pre Event", replace
la val ny ny
la var year_founded "Branch Founded"
la val post_event post_event
la def bank_failure_state 1 "Bank Failure in State", replace
la val bank_failure_state bank_failure_state


esttab win30* using output/jay_cooke_daily_30.tex, replace  ///
label noomit nobase eqlabels(none) eform scalars("bankfe Bank FE") star(* .1 ** .05 *** .01) ///
 nomtitles booktabs nonotes

// Table 4


clear
use working/sequential_records_with_geography
keep if new_account
gen nonwhite = white==0
replace local = . if white==1
replace organization = . if white==1
drop nonlocal
gen nonlocal = local==0
gen individual = organization==0
collapse (sum) new_account white nonwhite local nonlocal organization individual, by(date)

tsset date
tsfill, full
foreach var of varlist new_account white nonwhite local nonlocal organization individual {
	replace `var' = 0 if mi(`var')
}
drop if dow(date)==0
bcal create working/fbcal, from(date) replace

gen long fbdate = bofd("fbcal", date)
format fbdate %tbfbcal:M_d,_CY
tsset fbdate


xtbreak estimate new_account if year(date)>=1873, breakconstant breaks(3)
matrix CI1 = e(CI)
matrix breaks1 = e(breaks)

local group_label2 "White vs Nonwhite"
xtbreak estimate white if year(date)>=1873, breakconstant breaks(3)
matrix CI22 = e(CI)
matrix breaks22 = e(breaks)	
xtbreak estimate nonwhite if year(date)>=1873, breakconstant breaks(3)
matrix CI23 = e(CI)
matrix breaks23 = e(breaks)

local group_label3 "Local vs Nonlocal"
xtbreak estimate local if year(date)>=1873, breakconstant breaks(3)
matrix CI32 = e(CI)
matrix breaks32 = e(breaks)
xtbreak estimate nonlocal if year(date)>=1873, breakconstant breaks(3)
matrix CI33 = e(CI)
matrix breaks33 = e(breaks)

local group_label4 "Org vs Individual"
xtbreak estimate organization if year(date)>=1873, breakconstant breaks(3)
matrix CI42 = e(CI)
matrix breaks42 = e(breaks)
xtbreak estimate individual if year(date)>=1873, breakconstant breaks(3)
matrix CI43 = e(CI)
matrix breaks43 = e(breaks)


capture file close myfile
file open myfile using output/breaks.tex, write replace
file write myfile "%% Table 4: Structural Breaks in Depositor Composition" _n
forval y = 2/4 {
	file write myfile ("`group_label`y''") _n
	forval x = 1/3 {
		file write myfile "Regime `x'" _col(15) " & " %tbfbcal:M_d,_CY (breaks1[2,`x']) " & " %tbfbcal:M_d,_CY (breaks`y'2[2,`x']) " & " %tbfbcal:M_d,_CY (breaks`y'3[2,`x']) "  \\" _n
	}
	file write myfile _n _n "----------------------------" _n _n
}

file close myfile


// Table 5
clear
forval x = 1/3 {
	use working/stuctural_break_w`x'_window
	rename new_account new_account1 
	rename new_white_account new_account2 
	keep date bank city new_account1 new_account2 event_seq event_time event_date event post_event_date
	gen new_account3 = new_account1 - new_account2 
	reshape long new_account, i(date bank event_time) j(type)
	save working/stuctural_break_all`x'_window, replace
}






eststo drop *
use "working/stuctural_break_all2_window", clear
drop if city == "Philadelphia"
eststo: ppmlhdfe new_account post_event_date##type if inrange(date,mdy(12,31,1873)-30,mdy(12,31,1873)) & inlist(type,2,3), a(bank#type) vce(cluster bank)
eststo: ppmlhdfe new_account post_event_date##type if inrange(date,mdy(12,31,1873)-30,mdy(12,31,1873)) & inlist(type,2,3) & city!="New York", a(bank#type) vce(cluster bank)

use "working/stuctural_break_all3_window", clear
drop if city == "Philadelphia"
eststo: ppmlhdfe new_account post_event_date##type if inrange(date,mdy(4,9,1874)-30,mdy(4,9,1874)) & inlist(type,2,3), a(bank#type ) vce(cluster bank)
eststo: ppmlhdfe new_account post_event_date##type if inrange(date,mdy(4,9,1874)-30,mdy(4,9,1874)) & inlist(type,2,3) & city!="New York", a(bank#type) vce(cluster bank)

la define group, replace
la define group 3 "Non-White Depositors", add
la val type group 

la define post_event, replace
la define post_event 1 "Post Break Date", add
la val post_event post_event

esttab using output/white_depositor_arrival_diff_poisson.tex, replace  ///
label eqlabels(none)  star(* .1 ** .05 *** .01) ///
nobase noomit eform nonotes ///
nomtitles booktabs scalar("r2_p Pseudo-\(R^2\)") sfmt( "%5.3f")  



// Table 6
use working/sequential_records_with_geography, clear
keep if year>=1872 & new_account==1 &  city!="Philadelphia"
collapse (mean) pct_org = organization, by(bank)
save working/pct_org, replace

merge 1:m bank using working/weekly_closure_test_data, keep(match using) nogen 

compress
save working/closure_temp, replace

use working/sequential_records_with_geography, clear
recast str pr_name
tempfile temp1
save `temp1'

keep if organization
keep fs_pr_ark 
merge 1:1 fs_pr_ark using working/family_search_full
gen key_org_person = _merge==3
drop _merge

bys acct_id: egen tagged_org = max(key_org_person)
keep if tagged_org ==1
save working/tagged_orgs_all_persons, replace

keep if !mi(pr_name_surn)
keep city pr_name
duplicates drop
recast str pr_name
merge 1:m city pr_name using `temp1', keep(match using)
gen name_match = _merge==3 if organization==0
drop _merge
tempfile temp2
save `temp2'

keep if name_match==1
keep acct_id
unique acct_id
merge 1:1 acct_id using working/closure_temp, keep(match using)
gen in_org = _merge==3
drop _merge
save working/closure_temp, replace

use `temp2'
keep if new_account
bys city pr_name: gen unique_name_match = name_match if _n==1
collapse (mean) mean_org_rep = name_match mean_org_rep_unique = unique_name_match, by(bank)
save working/branch_org_data, replace
merge 1:m bank using working/closure_temp, keep(match using) nogen


egen org_frac = mean(organization), by(bank)
gen int branch_by_of = 0
la define branch_by_of, replace

tempvar firstobs global_obs
gen long `global_obs' = _n
bys org_frac (bank): gen `firstobs' = _n==1

levelsof `global_obs' if `firstobs', local(label_obs)
local i = 0
foreach g of local label_obs {
	local i = `i' + 1
	local branch_num = bank[`g']
	local branch_name: label bank_branch `branch_num'
	local labelval =  string(org_frac[`g'],"%5.3f" )
	qui replace branch_by_of = `i' if city=="`branch_name'"
	la define branch_by_of `i' "`branch_name' (`labelval')", add
}
la val branch_by_of branch_by_of
la var branch_by_of "Branch (% of org accts)"

la var in_org "Organization Member"
keep if year>=1873 /* Test only 1873 onward */


replace pre_panic_acct = 1 if year==1872

eststo drop *
eststo: reghdfe closed_account organization in_org white local in_town io(0 2).age_range io(0 3).job_education , a(missing_in_town missing_job_info missing_age missing_local bank#yearm) cluster(bank)

eststo: reghdfe closed_account organization in_org white local in_town io(0 2).age_range io(0 3).job_education if regime ==0, a(missing_in_town missing_job_info missing_age missing_local bank#yearm) cluster(bank)

eststo: reghdfe closed_account organization in_org white local in_town io(0 2).age_range io(0 3).job_education if regime ==1, a(missing_in_town missing_job_info missing_age missing_local bank#yearm) cluster(bank)

eststo: reghdfe closed_account organization in_org white local in_town io(0 2).age_range io(0 3).job_education if regime ==2, a(missing_in_town missing_job_info missing_age missing_local bank#yearm) cluster(bank)

eststo: reghdfe closed_account organization in_org white local in_town io(0 2).age_range io(0 3).job_education if regime ==3, a(missing_in_town missing_job_info missing_age missing_local bank#yearm) cluster(bank)

esttab using output/account_closure_test.tex, noomit nobase label order(white organization in_org local  local in_town) booktabs star(* .1 ** .05 *** .01) ar2 mtitles("Pooled" "Regime 1" "Regime 2" "Regime 3" "Regime 4") replace


// Table 7
use working/weekly_closure_test_data, clear

gen post_72 = date>=mdy(1,2,1873)
gen post_june_73 = date>=mdy(7,2,1873)
gen post_jc = date>=mdy(9,19,1873)
gen post_73 = date>=mdy(1,2,1874)
gen post_april = date>=mdy(4,1,1874)


eststo drop *

capture drop post_event
gen post_event = post_jc if inrange(date, mdy(8,19,1873),mdy(10,19,1873))
eststo: reghdfe closed_account  post_event if inrange(date, mdy(8,19,1873),mdy(10,19,1873)), a(organization white local missing_in_town age_range job_education missing_job_info missing_age missing_local bank) cluster(bank)

capture drop post_event
gen post_event = post_73 if inrange(date, mdy(12,1,1873),mdy(1,31,1874))
eststo: reghdfe closed_account  post_event if inrange(date, mdy(12,1,1873),mdy(1,31,1874)), a(organization white local missing_in_town age_range job_education missing_job_info missing_age missing_local bank) cluster(bank)

capture drop post_event
gen post_event = post_april if inrange(date, mdy(3,11,1874),mdy(5,11,1874))
eststo: reghdfe closed_account  post_event if inrange(date, mdy(3,11,1874),mdy(5,11,1874)), a(organization white local missing_in_town age_range job_education missing_job_info missing_age missing_local bank) cluster(bank)

esttab using output/short_window1.tex, nobase noomit mtitles("Sep 18, 1873" "Jan 1, 1874" "April 1,1873") star(* .1 ** .05 *** .01) r2 booktabs replace


eststo drop *

capture drop post_event
gen post_event = post_jc if inrange(date, mdy(8,19,1873),mdy(10,19,1873))
eststo: reghdfe closed_account  post_event##white if inrange(date, mdy(8,19,1873),mdy(10,19,1873)), a(organization white local missing_in_town age_range job_education missing_job_info missing_age missing_local bank) cluster(bank)

capture drop post_event
gen post_event = post_73 if inrange(date, mdy(12,1,1873),mdy(1,31,1874))
eststo: reghdfe closed_account  post_event##white if inrange(date, mdy(12,1,1873),mdy(1,31,1874)), a(organization white local missing_in_town age_range job_education missing_job_info missing_age missing_local bank) cluster(bank)

capture drop post_event
gen post_event = post_april if inrange(date, mdy(3,11,1874),mdy(5,11,1874))
eststo: reghdfe closed_account  post_event##white if inrange(date, mdy(3,11,1874),mdy(5,11,1874)), a(organization white local missing_in_town age_range job_education missing_job_info missing_age missing_local bank) cluster(bank)

esttab using output/short_window2.tex, nobase noomit mtitles("Sep 18, 1873" "Jan 1, 1874" "April 1,1873") star(* .1 ** .05 *** .01) r2 booktabs replace nonotes  


